package other.xsy.passlys.receivable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEvent;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventRequest;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventResponse;
import com.rkhd.platform.sdk.data.model.Contract;
import com.rkhd.platform.sdk.data.model.InvoiceDetail__c;
import com.rkhd.platform.sdk.data.model.Invoice__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.xsy.passlys.util.HCXObjectService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 开票明细新增、编辑、修改时，同步修改相关的开票金额字段
 * @Author 黎炎松
 * 2024-08-08 15:59
 */
public class InvoiceDetailRuleevent implements RuleEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "开票明细进行变更时,修改相关的开票金额字段 ==> ";

    public static void main(String[] args) {
        InvoiceDetailRuleevent invoiceDetailRuleevent = new InvoiceDetailRuleevent();
        RuleEventRequest request = new RuleEventRequest();
        request.setDataId(3411888499907227L);
        invoiceDetailRuleevent.execute(request);
    }

    /**
     * 触发规则触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public RuleEventResponse execute(RuleEventRequest request) {
        Long dataId = request.getDataId();
        logger.info(LOGGER_MSG + "触发开始 dataId = " + dataId);
        try {
            InvoiceDetail__c invoiceDetail = new InvoiceDetail__c();
            invoiceDetail.setId(dataId);
            invoiceDetail = hcxObjectService.get(invoiceDetail);

            // 获取booking 计算相关的开票金额字段
            if (invoiceDetail.getBooking__c() != null) {
                ReceivableService receivableService = new ReceivableService();
                receivableService.calcInvoiceAmounByBooking(Arrays.asList(invoiceDetail.getBooking__c()));
            }

            // 回写主表的明细字段 （产品名称+阶段名称）
            logger.info(LOGGER_MSG + "处理开票明细回写");
            Long invoiceId = invoiceDetail.getInvoice__c();
            String sql = "select id,invoiceName__c,receivablePhase__c,booking__c from invoiceDetail__c where invoice__c = " + invoiceId;
            List<JSONObject> records = XoqlService.instance().query(sql, true).getRecords();
            List<String> strList = new ArrayList<>();
            List<Long> bookingIdList = new ArrayList<>();
            for (JSONObject record : records) {
                Long bookingId = record.getLong("booking__c");
                if (!bookingIdList.contains(bookingId)) {
                    bookingIdList.add(bookingId);
                }
                strList.add(record.getString("invoiceName__c") + "-" + getOptionStr(record.getJSONArray("receivablePhase__c")));
            }

            Invoice__c invoice = new Invoice__c();
            invoice.setId(invoiceId);
            invoice.setMessage__c(StringUtils.join(strList, ","));
            invoice.setBookingStr__c(StringUtils.join(bookingIdList, ","));
            Boolean update = hcxObjectService.update(invoice);
            logger.info(LOGGER_MSG + "update: " + update);

            logger.info(LOGGER_MSG + "执行结束");
        } catch (ApiEntityServiceException e) {
            throw new RuntimeException(e);
        }
        RuleEventResponse response = new RuleEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    /**
     * 获取选项的字符串值
     * @param optionArr
     * @return
     */
    public String getOptionStr(JSONArray optionArr) {
        String optStr = "";
        if (optionArr != null && optionArr.size() > 0) {
            optStr = optionArr.stream().map(v -> v.toString()).collect(Collectors.joining(","));
        }
        return optStr;
    }
}
